<template>
  <div class="character-detail">
    <div class="header">
      <el-button class="back-btn" @click="goBack">
        <el-icon><ArrowLeft /></el-icon>
      </el-button>
      <div class="actions">
        <el-button class="collect-btn" :class="{ collected: isCollected }" @click="toggleCollect">
          <el-icon><Star /></el-icon>
        </el-button>
      </div>
    </div>

    <div class="main-content">
      <div class="character-showcase">
        <div class="image-container">
          <img :src="characterData.image" 
               :alt="characterData.character" 
               class="character-image" 
               :class="{ 
                 'black-and-white': isBlackAndWhite,
                 'with-grid': selectedGrid !== 'none'
               }" 
               ref="mainImage"/>
          <div v-if="selectedGrid !== 'none'" 
               :class="['grid-overlay', `grid-${selectedGrid}`]">
          </div>
        </div>
        <h1 class="character">{{ characterData.character }}</h1>
        
        <div class="function-buttons">
          <div class="function-item">
            <button class="function-btn" @click="downloadImage">下载</button>
          </div>
          <div class="function-item">
            <button class="function-btn" :class="{ active: isBlackAndWhite }" @click="toggleBlackAndWhite">
              {{ isBlackAndWhite ? '原色' : '黑白' }}
            </button>
          </div>
          <div class="function-item">
            <button class="function-btn" 
                    :class="{ active: selectedGrid !== 'none' }" 
                    @click="toggleGridMenu">
              {{ selectedGrid === 'none' ? '线格' : '关闭' }}
            </button>
          </div>
          <div class="function-item">
            <button class="function-btn">同字搜索</button>
          </div>
        </div>
      </div>

      <div class="info-section">
        <div class="info-card">
          <div class="next-characters">
            <div v-for="(char, index) in nextCharacters" 
                 :key="index" 
                 class="next-char-item">
              <img :src="char.image" :alt="char.character"/>
              <span>{{ char.character }}</span>
            </div>
          </div>
        </div>
      </div>
    </div>

    <el-dialog
      v-model="showGridMenu"
      title="选择线格样式"
      width="400px"
      align-center
      :show-close="false"
      class="grid-dialog"
    >
      <div class="grid-options">
        <div class="grid-option" 
             v-for="option in gridOptions" 
             :key="option.value"
             :class="{ active: tempSelectedGrid === option.value }"
             @click="selectGrid(option.value)">
          <div class="grid-preview" :class="`preview-${option.value}`">
            <template v-if="option.value === 'square'">
              <div v-for="i in 9" :key="i"></div>
            </template>
          </div>
          <span>{{ option.label }}</span>
        </div>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button class="dialog-btn" @click="showGridMenu = false">取消</el-button>
          <el-button class="dialog-btn" type="primary" @click="confirmGridSelection">确定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { 
  ArrowLeft, 
  Star, 
  Download, 
  Grid, 
  MoonNight, 
  Search 
} from '@element-plus/icons-vue'
import ziIcon from '@/assets/zi_icon.png'
import { saveAs } from 'file-saver'
import type { Ref } from 'vue'

const route = useRoute()
const router = useRouter()
const isCollected = ref(false)
const isBlackAndWhite = ref(false)
const mainImage = ref<HTMLImageElement | null>(null)
const selectedGrid = ref<'none' | 'square' | 'field' | 'star'>('none')
const showGridMenu = ref(false)

const gridOptions = [
  { label: '方格', value: 'square' },
  { label: '田字格', value: 'field' },
  { label: '米字格', value: 'star' }
] as const

const tempSelectedGrid = ref<'none' | 'square' | 'field' | 'star'>('none')

// 模拟字符数据
const characterData = ref({
  character: '永',
  image: ziIcon,
  meaning: '永字八法是书法基本笔画的典范...',
  analysis: '永字在书法中占有重要地位，其结构包含了书法的基本笔画...',
  similarChars: [
    { character: '永', image: ziIcon },
    { character: '永', image: ziIcon },
    { character: '永', image: ziIcon },
    { character: '永', image: ziIcon },
    { character: '永', image: ziIcon },
    { character: '永', image: ziIcon },
  ]
})

const nextCharacters = ref(history.state?.nextCharacters || [])

const goBack = () => {
  router.push({
    name: 'Show'
  })
}

const toggleCollect = () => {
  isCollected.value = !isCollected.value
}

const downloadImage = async () => {
  try {
    const canvas = document.createElement('canvas')
    const ctx = canvas.getContext('2d')
    if (!ctx || !mainImage.value) return
    
    canvas.width = mainImage.value.naturalWidth
    canvas.height = mainImage.value.naturalHeight
    
    // 直接使用当前显示的图片（包含黑白效果）
    ctx.drawImage(mainImage.value, 0, 0)

    // 如果选择了线格，绘制线格
    if (selectedGrid.value !== 'none') {
      ctx.strokeStyle = 'rgba(255, 0, 0, 0.2)'
      ctx.lineWidth = 2

      if (selectedGrid.value === 'square') {
        // 绘制方格（九宫格样式）
        const cellSize = canvas.width / 3
        
        // 绘制外框
        ctx.strokeRect(0, 0, canvas.width, canvas.height)
        
        // 绘制内部线条
        for (let i = 1; i < 3; i++) {
          // 垂直线
          ctx.beginPath()
          ctx.moveTo(cellSize * i, 0)
          ctx.lineTo(cellSize * i, canvas.height)
          ctx.stroke()
          
          // 水平线
          ctx.beginPath()
          ctx.moveTo(0, cellSize * i)
          ctx.lineTo(canvas.width, cellSize * i)
          ctx.stroke()
        }
      } else if (selectedGrid.value === 'field') {
        // 田字格
        ctx.beginPath()
        
        // 绘制外框
        ctx.strokeRect(0, 0, canvas.width, canvas.height)
        
        // 绘制十字
        ctx.beginPath()
        // 垂直线
        ctx.moveTo(canvas.width / 2, 0)
        ctx.lineTo(canvas.width / 2, canvas.height)
        // 水平线
        ctx.moveTo(0, canvas.height / 2)
        ctx.lineTo(canvas.width, canvas.height / 2)
        ctx.stroke()

      } else if (selectedGrid.value === 'star') {
        // 米字格
        // 绘制外框
        ctx.strokeRect(0, 0, canvas.width, canvas.height)
        
        // 绘制十字线
        ctx.beginPath()
        // 垂直线
        ctx.moveTo(canvas.width / 2, 0)
        ctx.lineTo(canvas.width / 2, canvas.height)
        // 水平线
        ctx.moveTo(0, canvas.height / 2)
        ctx.lineTo(canvas.width, canvas.height / 2)
        ctx.stroke()
        
        // 绘制对角线
        ctx.beginPath()
        // 左上到右下
        ctx.moveTo(0, 0)
        ctx.lineTo(canvas.width, canvas.height)
        // 右上到左下
        ctx.moveTo(canvas.width, 0)
        ctx.lineTo(0, canvas.height)
        ctx.stroke()
      }
    }
    
    // 将 canvas 转为 blob
    const blob = await new Promise<Blob>((resolve) => {
      canvas.toBlob((blob) => {
        if (blob) resolve(blob)
      }, 'image/png')
    })
    
    // 下载文件
    const fileName = `${characterData.value.character}.png`
    saveAs(blob, fileName)
  } catch (error) {
    console.error('下载失败:', error)
  }
}

const toggleBlackAndWhite = () => {
  isBlackAndWhite.value = !isBlackAndWhite.value
  
  if (!mainImage.value) return
  
  // 创建一个临时 canvas 来处理图片
  const canvas = document.createElement('canvas')
  const ctx = canvas.getContext('2d')
  if (!ctx) return
  
  canvas.width = mainImage.value.naturalWidth
  canvas.height = mainImage.value.naturalHeight
  
  // 绘制原始图片到 canvas
  ctx.drawImage(mainImage.value, 0, 0)
  
  if (isBlackAndWhite.value) {
    // 获取图片数据
    const imageData = ctx.getImageData(0, 0, canvas.width, canvas.height)
    const data = imageData.data
    
    // 使用 OTSU 算法自动计算最佳阈值
    let histogram = new Array(256).fill(0)
    for (let i = 0; i < data.length; i += 4) {
      const avg = Math.round((data[i] + data[i + 1] + data[i + 2]) / 3)
      histogram[avg]++
    }
    
    let sum = 0
    let sumB = 0
    let wB = 0
    let wF = 0
    let max = 0.0
    let threshold = 0
    const total = data.length / 4
    
    for (let i = 0; i < 256; i++) {
      sum += i * histogram[i]
    }
    
    for (let i = 0; i < 256; i++) {
      wB += histogram[i]
      if (wB === 0) continue
      
      wF = total - wB
      if (wF === 0) break
      
      sumB += i * histogram[i]
      
      const mB = sumB / wB
      const mF = (sum - sumB) / wF
      
      const between = wB * wF * (mB - mF) * (mB - mF)
      
      if (between > max) {
        max = between
        threshold = i
      }
    }
    
    // 应用阈值进行二值化
    for (let i = 0; i < data.length; i += 4) {
      const avg = (data[i] + data[i + 1] + data[i + 2]) / 3
      const value = avg > threshold ? 255 : 0
      data[i] = data[i + 1] = data[i + 2] = value
    }
    
    ctx.putImageData(imageData, 0, 0)
    
    // 更新图片源
    const newImageUrl = canvas.toDataURL('image/png')
    mainImage.value.src = newImageUrl
  } else {
    // 恢复原图
    mainImage.value.src = characterData.value.image
  }
}

const toggleGridMenu = () => {
  if (selectedGrid.value !== 'none') {
    selectedGrid.value = 'none'
  } else {
    tempSelectedGrid.value = selectedGrid.value
    showGridMenu.value = true
  }
}

const selectGrid = (gridType: 'square' | 'field' | 'star') => {
  tempSelectedGrid.value = gridType
}

const confirmGridSelection = () => {
  selectedGrid.value = tempSelectedGrid.value
  showGridMenu.value = false
}

onMounted(() => {
  const state = history.state
  if (state && state.characterImage) {
    characterData.value.image = state.characterImage
    characterData.value.character = route.params.id as string
  }
})
</script>

<style scoped>
.character-detail {
  padding: 20px;
  max-width: 1200px;
  margin: 0 auto;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 30px;
}

.back-btn,
.collect-btn {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  padding: 0;
  display: flex;
  align-items: center;
  justify-content: center;
  background: #fff;
  border: none;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.character-showcase {
  text-align: center;
  margin-bottom: 40px;
  display: flex;
  flex-direction: column;
  align-items: center;
}

.function-buttons {
  display: flex;
  justify-content: center;
  gap: 20px;
  margin-top: 30px;
  width: 100%;
  max-width: 400px;
}

.function-item {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.function-btn {
  padding: 8px 15px;
  font-size: 14px;
  background-color: transparent;
  color: #3498db;
  border: 2px solid #3498db;
  border-radius: 4px;
  cursor: pointer;
  transition: background-color 0.3s, color 0.3s;
  min-width: 80px;
}

.function-btn:hover {
  background-color: #3498db;
  color: white;
}

.function-btn.active {
  background-color: #3498db;
  color: white;
}

.character-image {
  width: 160px;
  height: 160px;
  object-fit: contain;
  margin-bottom: 20px;
}

.character {
  font-size: 36px;
  margin: 0 0 20px 0;
}

.info-section {
  margin-top: 20px;
  display: flex;
  flex-direction: column;
  gap: 16px;
}


.info-card h2 {
  font-size: 18px;
  color: #333;
  margin-bottom: 12px;
  font-weight: 500;
}

.info-card p {
  color: #666;
  line-height: 1.6;
  margin: 0;
}

.collect-btn.collected {
  color: #ffd700;
}

.character-image.black-and-white {
  filter: grayscale(100%);
}

.image-container {
  position: relative;
  width: 160px;
  height: 160px;
  margin-bottom: 20px;
}

.grid-overlay {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  pointer-events: none;
  border: 2px solid rgba(255, 0, 0, 0.2);
}

.grid-square {
  background-image: linear-gradient(to right, rgba(255, 0, 0, 0.2) 1px, transparent 1px),
                    linear-gradient(to bottom, rgba(255, 0, 0, 0.2) 1px, transparent 1px);
  background-size: 33.33% 33.33%;
}

.grid-field {
  &::before, &::after {
    content: '';
    position: absolute;
    background: rgba(255, 0, 0, 0.2);
  }
  &::before {
    top: 50%;
    left: 0;
    width: 100%;
    height: 1.5px;
  }
  &::after {
    left: 50%;
    top: 0;
    width: 1.5px;
    height: 100%;
  }
}

.grid-star {
  &::before {
    content: '';
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background: 
      linear-gradient(45deg, transparent 49.5%, rgba(255, 0, 0, 0.2) 49.5%, rgba(255, 0, 0, 0.2) 50.5%, transparent 50.5%),
      linear-gradient(-45deg, transparent 49.5%, rgba(255, 0, 0, 0.2) 49.5%, rgba(255, 0, 0, 0.2) 50.5%, transparent 50.5%),
      linear-gradient(to right, transparent 49.5%, rgba(255, 0, 0, 0.2) 49.5%, rgba(255, 0, 0, 0.2) 50.5%, transparent 50.5%),
      linear-gradient(to bottom, transparent 49.5%, rgba(255, 0, 0, 0.2) 49.5%, rgba(255, 0, 0, 0.2) 50.5%, transparent 50.5%);
  }
}

.grid-dialog :deep(.el-dialog__body) {
  padding: 20px;
}

.grid-dialog :deep(.el-dialog__header) {
  margin-right: 0;
  padding: 20px 20px 10px;
}

.grid-dialog :deep(.el-dialog__title) {
  font-size: 18px;
  font-weight: 500;
}

.grid-dialog :deep(.el-dialog__footer) {
  padding: 10px 20px 20px;
  border-top: none;
}

.grid-options {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 16px;
  padding: 10px;
  width: fit-content;
  margin: 0 auto;
}

.grid-option {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 8px;
  cursor: pointer;
  padding: 10px;
  border-radius: 8px;
  transition: all 0.3s ease;
  border: 2px solid transparent;
}

.grid-option:hover {
  background-color: #f5f5f5;
}

.grid-option.active {
  background-color: #e6f7ff;
  border: 2px solid #3498db;
  transform: scale(1.05);
}

.grid-preview {
  width: 60px;
  height: 60px;
  border: 1px solid #ddd;
  border-radius: 4px;
  position: relative;
  background-color: white;
}

.preview-square {
  border: 1px solid rgba(255, 0, 0, 0.2);
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  grid-template-rows: repeat(3, 1fr);
  gap: 0;
  & > div {
    border-right: 1px solid rgba(255, 0, 0, 0.2);
    border-bottom: 1px solid rgba(255, 0, 0, 0.2);
    &:nth-child(3n) {
      border-right: none;
    }
    &:nth-child(n+7) {
      border-bottom: none;
    }
  }
}

.preview-field {
  position: relative;
  &::before, &::after {
    content: '';
    position: absolute;
    background: rgba(255, 0, 0, 0.2);
  }
  &::before {
    top: 50%;
    left: 0;
    width: 100%;
    height: 1px;
  }
  &::after {
    left: 50%;
    top: 0;
    width: 1px;
    height: 100%;
  }
  border: 1px solid rgba(255, 0, 0, 0.2);
}

.preview-star {
  position: relative;
  &::before {
    content: '';
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background: 
      linear-gradient(45deg, transparent 49.5%, rgba(255, 0, 0, 0.2) 49.5%, rgba(255, 0, 0, 0.2) 50.5%, transparent 50.5%),
      linear-gradient(-45deg, transparent 49.5%, rgba(255, 0, 0, 0.2) 49.5%, rgba(255, 0, 0, 0.2) 50.5%, transparent 50.5%),
      linear-gradient(to right, transparent 49.5%, rgba(255, 0, 0, 0.2) 49.5%, rgba(255, 0, 0, 0.2) 50.5%, transparent 50.5%),
      linear-gradient(to bottom, transparent 49.5%, rgba(255, 0, 0, 0.2) 49.5%, rgba(255, 0, 0, 0.2) 50.5%, transparent 50.5%);
  }
  border: 1px solid rgba(255, 0, 0, 0.2);
}

.dialog-footer {
  display: flex;
  justify-content: center;
  gap: 16px;
  padding-top: 20px;
}

.dialog-btn {
  min-width: 80px;
}

.next-characters {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 16px;
  margin-top: 20px;
}

.next-char-item {
  text-align: center;
  padding: 12px;
  cursor: pointer;
  transition: all 0.3s ease;
}

.next-char-item:hover {
  transform: scale(1.05);
  background-color: rgba(255, 255, 255, 0.1);
}

.next-char-item img {
  width: 60px;
  height: 60px;
  object-fit: contain;
  margin-bottom: 8px;
  transition: all 0.3s ease;
}

.next-char-item:hover img {
  filter: brightness(1.1);
}

.next-char-item span {
  display: block;
  font-size: 14px;
  color: #333;
  transition: all 0.3s ease;
}

.next-char-item:hover span {
  color: #409EFF;
}

.info-card {
  background: transparent;
}
</style> 